<template>
  <div class="g-page-container">
    <PageHeader title="价格台账" />
    <div class="g-content-container">
      <PriceSearchForm ref="search-form" @search="loadTableList" />
      <ButtonGroup :options="middleButtons" @click="handleButtonClick" />
      <PriceChangeTableList
        :loading="loading"
        :data-source="totalData"
        :columns="columns"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>
    <DialogColumnsNum
      :visible.sync="visibleModal"
      :fileds="fileds"
      @confirm="handleSelectFileds"
    />
    <DialogBpForecastRelationList
      :value="currentRowInfo.value"
      :visible="visibleBpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.bpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleBpId = val)"
      @change="(e) => confirmDialog(e)"
    />
    <DialogRpRelationList
      :value="currentRowInfo.value"
      :visible="visibleRpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.rpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleRpId = val)"
      @change="(e) => confirmDialog(e)"
    />
  </div>
</template>

<script>
import PriceSearchForm from './components/PriceSearchForm.vue';
import DialogColumnsNum from './components/DialogColumnsNum.vue';
// import mixinTable from '@/mixins/mixin-table.js';
import DialogBpForecastRelationList from '@/components/dialog/DialogBpForecastRelationList.vue';
import DialogRpRelationList from '@/components/dialog/DialogRpRelationList.vue';

import PriceChangeTableList from './components/PriceChangeTableList.vue';
import ColumnsTooltip from './components/columnsTooltip.vue';

import {
  postPriceParameterList,
  postExportPriceParameterDetail,
} from '@/api/price.js';
import monent from 'moment';
import { createMonthArray } from '@/utils/time';
import { downloadFile } from '@/utils/index.js';
import Decimal from 'decimal.js';

export default {
  components: {
    PriceSearchForm,
    PriceChangeTableList,
    DialogBpForecastRelationList,
    DialogRpRelationList,
    // eslint-disable-next-line vue/no-unused-components
    ColumnsTooltip,
    DialogColumnsNum,
  },
  // mixins: [mixinTable],
  data() {
    return {
      asc: true,
      // columnKey: '',
      loading: false,
      dataSource: [],
      // selectedInfos: [],
      visibleModal: false,
      // processId: undefined,
      formData: {},
      filedsKeys: [],
      exportData: [],
      dateNeedList: [],
      isDateChange: false,
      visibleBpId: false,
      visibleRpId: false,
      currentRowInfo: {},
      resultDate: {}
    };
  },
  computed: {
    timeRange() {
      let isDate = this.resultDate.length
      console.log([this.resultDate[0], this.resultDate[isDate - 1]])
      return isDate && [this.resultDate[0], this.resultDate[isDate - 1]];
    },
    fileds() {
      // let index = this.defaultCoulumns?.findIndex((item) => {
      //   return item.dataIndex === 'remark'
      // })
      // return this.defaultCoulumns.slice(0, index + 1)
      return this.defaultCoulumns;
    },
    middleButtons() {
      return [
        {
          key: 'view',
          label: '显示字段',
          auth: true,
        },
        {
          key: 'export',
          label: '导出',
          auth: true,
        },
      ];
    },
    groups() {
      let data = this.dataSource.reduce((pre, cur) => {
        if (pre[cur.salesGroupName]) {
          pre[cur.salesGroupName].push(cur);
        } else {
          pre[cur.salesGroupName] = [cur];
        }
        return pre;
      }, {});
      return data;
    },
    totalData() {
      if (!this.dataSource.length) return [];
      // const totalKeys = Object.keys(this.dataSource[0]).filter((item) =>
      //   item.includes('Month')
      // );
      const totalKeys = this.getDateArr.map((item) => {
        const priceList = [`priceMonth${item}`];
        const newPriceList = [`newPriceMonth${item}`];
        const bpPriceList = [`bpPriceMonth${item}`];
        const rpPriceList = [`rpPriceMonth${item}`];
        return [...priceList, ...newPriceList, ...bpPriceList, ...rpPriceList];
      });
      // console.log(totalKeys.flat(1), 'totalKeys===123');

      if (this.getDateArr.length) {
        const data = Object.keys(this.groups).map((group) => {
          const obj = this.groups[group].reduce(
            (pre, cur) => {
              totalKeys.flat(1).forEach((key) => {
                if (!pre[key]) {
                  pre[key] = 0;
                }
                const numVal = new Decimal(pre[key]).plus(
                  new Decimal(cur[key] || 0)
                );
                pre[key] = numVal.toFixed(2);
              });
              return pre;
            },
            { id: 'totalKey' }
          );
          this.calcVal(obj);
          return [...this.groups[group], { ...this.groups[group][0], ...obj }];
        });

        const obj = this.dataSource.reduce(
          (pre, cur) => {
            totalKeys.flat(1).forEach((key) => {
              if (!pre[key]) {
                pre[key] = 0;
              }
              const numVal = new Decimal(pre[key]).plus(
                new Decimal(cur[key] || 0)
              );
              pre[key] = numVal.toFixed(2);
            });
            return pre;
          },
          { id: 'totalKey' }
        );
        this.calcVal(obj);
        // console.log(obj, 'obj========123')
        if (Object.keys(this.groups).length > 1) {
          // console.log([...data.flat(1), { ...this.dataSource[0], ...obj }], 'list123');
          return [...data.flat(1), { ...this.dataSource[0], ...obj }];
        }

        return data.flat(1);
      }
      return this.dataSource;
    },
    colIndex() {
      return this.columns.findIndex((item) => item.dataIndex === 'priceMonth0');
    },
    totalAllIndex() {
      return this.totalData.reduce((pre, cur, index) => {
        if (cur.id === 'totalKey') {
          pre.push(index);
        }
        return pre;
      }, []);
    },
    getDateArr() {
      // if (
      //   !this.formData.startTime ||
      //   !this.formData.endTime ||
      //   this.formData.startTime === 'Invalid date 00:00:00' ||
      //   this.formData.endTime === 'Invalid date 00:00:00'
      // ) {
      //   this.currentDate();
      // }

      // const startTime = monent(this.formData.startTime).format('YYYY-MM');
      // const endTime = monent(this.formData.endTime).format('YYYY-MM');
      // const ranges = createMonthArray([startTime, endTime]);
      return this.resultDate || [];
    },

    defaultCoulumns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 60,
          required: true,
          // customRender(t, r, index) {
          //   return parseInt(index) + 1;
          // },
          customRender: (t, r, index) => {
            if (this.totalAllIndex.includes(index)) {
              return {
                children: (
                  <div style="display: flex;justify-content: flex-start;">
                    {index === this.totalData.length - 1 &&
                    Object.keys(this.groups).length > 1
                      ? '大汇总'
                      : '组内汇总'}
                  </div>
                ),
                attrs: {
                  colSpan: this.colIndex,
                },
              };
            }
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupName',
          key: 'salesGroupName',
          width: 80,
          // sorter: true,
          required: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index, row, 'salesGroupName');
          },
        },
        {
          align: 'center',
          title: 'M+9关系ID',
          dataIndex: 'm9RelationId',
          key: 'm9RelationId',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联RP关系ID',
          dataIndex: 'rpRelationId',
          key: 'rpRelationId',
          width: 120,
          ellipsis: true,
          customRender: (value, row, index) => {
            // const children = <ColumnsTooltip value={value} />;
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleRpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'rpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联BP关系ID',
          dataIndex: 'bpRelationId',
          key: 'bpRelationId',
          width: 120,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleBpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'bpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '厂区',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={this.factoryCodeChange[value]} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },

        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          key: 'modelInfoName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          key: 'modelName',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '料号',
          dataIndex: 'materialCode',
          key: 'materialCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          width: 80,
          dataIndex: 'manufactureArea',
          key: 'manufactureArea',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <ColumnsTooltip value={this.productionPlaceSate[value]} />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          key: 'application',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <ColumnsTooltip value={this.applicationState[value]} />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          width: 80,
          dataIndex: 'modelCutRate',
          key: 'modelCutRate',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          key: 'appearance',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={this.shapeState[value]} />;
            return this.customRender(children, index);
          },
        },

        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          key: 'item',
          width: 80,
          // ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          key: 'innerItem',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '类别',
          dataIndex: 'category',
          key: 'category',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={this.categoryChange[value]} />;
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          width: 100,
          dataIndex: 'remark',
          key: 'remark',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = <ColumnsTooltip value={value} />;
            return this.customRender(children, index);
          },
        },
      ];
      if (this.getDateArr.length) {
        this.getDateArr.forEach((date, i) => {
          columns.push({
            align: 'center',
            title: date,
            dataIndex: `priceMonth${i}`,
            width: 230,
            ellipsis: true,
            required: true,
            children: [
              {
                align: 'center',
                title: 'BP',
                dataIndex: `bpPriceMonth${date}`,
                key: `bpPrice${date}`,
                width: 80,
                ellipsis: true,
                scopedSlots: {
                  customRender: `bpPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  const children = <ColumnsTooltip value={value} />;
                  return {
                    children,
                  };
                },
              },
              {
                align: 'center',
                title: 'RP',
                dataIndex: `rpPriceMonth${date}`,
                key: `rpPrice${date}`,
                width: 80,
                ellipsis: true,
                scopedSlots: {
                  customRender: `rpPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  const children = <ColumnsTooltip value={value} />;
                  return {
                    children,
                  };
                },
              },
              {
                align: 'center',
                title: 'M+9',
                dataIndex: `priceMonth${date}`,
                key: `price${date}`,
                width: 80,
                ellipsis: true,
                scopedSlots: {
                  customRender: `priceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  const children = <ColumnsTooltip value={value} />;
                  return {
                    children,
                  };
                },
              },
              {
                align: 'center',
                title: '最新价格',
                dataIndex: `newPriceMonth${date}`,
                key: `newPrice${date}`,
                width: 80,
                ellipsis: true,
                scopedSlots: {
                  customRender: `newPriceMonth${date}`,
                },
                customRender: (value, row, index) => {
                  const children = <ColumnsTooltip value={value} />;
                  return {
                    children,
                  };
                },
              },
            ],
          });
        });
      }
      // console.log(columns);
      return columns;
    },
    columns() {
      let columns = this.defaultCoulumns.filter((item) => !item.isHide);
      if (this.filedsKeys.length) {
        columns = columns.filter((item) => {
          return item.required || this.filedsKeys.includes(item.dataIndex);
        });
      }
      return columns;
    },
    applicationState() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    categoryChange() {
      return this.$store.state.dictionary.dict['category'] || {};
    },
    factoryCodeChange() {
      return this.$store.state.dictionary.dict['factory_code'] || {};
    },
    shapeState() {
      return this.$store.state.dictionary.dict['shape'] || {};
    },
    productionPlaceSate() {
      return this.$store.state.dictionary.dict['production_place'] || {};
    },
  },
  created() {
    // this.loadTableList();
    this.$nextTick(() => {
      this.getPriceParameterDataList();
    });
  },
  methods: {
    openDialog(dialog, rowInfo) {
      this[dialog] = true;
      this.currentRowInfo = rowInfo;
      console.log('this.currentRowInfo: ', this.currentRowInfo);
    },
    calcVal(obj) {
      for (let i in obj) {
        if (obj[i] !== 'totalKey' && !+obj[i]) {
          obj[i] = '-';
        }
      }
    },
    // currentDate() {
    //   // let currentYearDate = '',
    //   // nextYearDate = '',
    //   // date = new Date(),
    //   // currentYear = date.getFullYear(),
    //   // currentMonth = date.getMonth() + 1;

    //   // let halfYear = 365 * 24 * 3600 * 1000,
    //   // nextResult = +date + halfYear,
    //   // nextDate = new Date(nextResult),
    //   // nextYear = nextDate.getFullYear(),
    //   // nextMonth = nextDate.getMonth();

    //   // currentYearDate = `${currentYear}-${currentMonth}`;
    //   // nextYearDate = `${nextYear}-${nextMonth}`;
    //   // this.formData.startTime = currentYearDate
    //   // this.formData.endTime = nextYearDate
    //   this.formData.startTime = `${monent().format('YYYY-MM-DD')} 00:00:00`;
    //   this.formData.endTime = `${monent()
    //     .add(1, 'years')
    //     .subtract(1, 'months')
    //     .format('YYYY-MM-DD')} 00:00:00`;
    // },
    handleSelectFileds(filedsKeys) {
      this.filedsKeys = filedsKeys;
    },
    customRender(children, index, row, key) {
      // console.log(index, str, 'children, index, row, key--------------------123')
      const attrs = {};
      if (this.totalAllIndex.includes(index)) {
        attrs.colSpan = 0;
      }
      if (key === 'salesGroupName') {
        const data = this.groups[row.salesGroupName];
        if (row.id === data[0].id) {
          attrs.rowSpan = data.length;
        } else {
          attrs.rowSpan = 0;
        }
      }
      return {
        children,
        attrs,
      };
    },
    async getPriceParameterDataList() {
      let data = this.$refs['search-form']?.getSearchParams;
      this.loading = true;
      try {
        // let start = `${monent().format('YYYY-MM-DD')} 00:00:00`;
        // let end = `${monent()
        //   .add(1, 'years')
        //   .subtract(1, 'months')
        //   .format('YYYY-MM-DD')} 00:00:00`;
        const res = await postPriceParameterList({
          ...data,
          // startTime: start,
          // endTime: end,
        });
        let dataList = res?.data?.data;
        this.exportData = dataList;
        this.dataSource = this.proessData(dataList) || [];
        this.resultDate = this.caclDate(dataList);
        console.log(this.caclDate(dataList))
        this.loading = false;
      } catch (err) {
        console.log(err, 'err');
        this.loading = false;
      }
    },
    proessData(data) {
      return (data || []).map((item) => {
        let price = this.dateVal('priceMonth', JSON.parse(item.price));
        let newPrice = this.dateVal('newPriceMonth', JSON.parse(item.newPrice));
        let bpPrice = this.dateVal('bpPriceMonth', JSON.parse(item.bpPrice));
        let rpPrice = this.dateVal('rpPriceMonth', JSON.parse(item.rpPrice));
        return {
          ...item,
          ...price,
          ...newPrice,
          ...bpPrice,
          ...rpPrice,
        };
      });
    },
    dateVal(val, typeObj) {
      let obj = {};
      for (let v in typeObj) {
        obj[`${val}${v}`] = typeObj[v];
      }
      return obj;
    },
    handleNumberClick(record) {
      console.log(record);
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.getSearchParams || {};
      // let { startTime, endTime } = form;
      // form.startTime = startTime
      //   ? `${monent(startTime).format('YYYY-MM-DD')} 00:00:00`
      //   : '';
      // form.endTime = endTime
      //   ? `${monent(endTime).format('YYYY-MM-DD')} 00:00:00`
      //   : '';
      return { ...form };
    },
    async loadTableList() {
      let formDate = this.getSearchForm();
      // 校验时间是否只输入一个
      // if (!formDate.startTime && formDate.endTime) {
      //   this.$message.error('请选择开始时间');
      //   return;
      // }
      // if (formDate.startTime && !formDate.endTime) {
      //   this.$message.error('请选择结束时间');
      //   return;
      // }
      this.formData = formDate;
      this.loading = true;
      try {
        const result = await postPriceParameterList(this.formData);
        this.loading = false;
        this.exportData = result?.data?.data;
        this.dataSource = this.proessData(result?.data?.data);
        this.resultDate = this.caclDate(result?.data?.data);
        this.loading = false;
      } catch (err) {
        console.log(err);
        this.loading = false;
      }
    },
    caclDate(data) {
      let date = data[0]?.price;
      let dateArr = Object.keys(
        JSON.parse(date)
      );
      return dateArr;
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      // this.columnKey = sorter.columnKey;
      // this.paginationMixin = page;
      // this.loadTableList();
    },
    handleButtonClick(key) {
      // console.log(key);
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    async exportCallback() {
      const data = JSON.parse(JSON.stringify(this.exportData));
      const res = await postExportPriceParameterDetail([...data]);
      await downloadFile(res.data, res.filename || '价格台账明细.xls');
    },
    async viewCallback() {
      this.visibleModal = true;
    },
  },
};
</script>

<style lang="less" scoped>
.table-container {
  padding: 15px 20px;
  height: calc(100vh - 160px);
  box-sizing: border-box;
}
</style>
